%	Initialization
clear; close all; clc;

%	========	Part 1: Feature Normalization	========
fprintf('Loading the data ...\n');
%	Load the data --- read comma separated data
data = load('data2.txt');
%   Initialize the variables of data
X = data(:, 1:2);
y = data(:, 3);
%   Number of the training examples
m = length(y);
fprintf('Normalizing the features ...\n');
%	Scale features and set them to zero mean
[X, mu, sigma] = featureNormalize(X);

%	========	Part 2: Gradient Descent	========
fprintf('Running the gradient descent ...\n');
%   Add a column of ones to X
X = [ones(m, 1), X];
%   Initialize the fitting parameters
theta = zeros(3, 1);
%   Gradient descent settings
iterations = 400;
alpha = 0.01;
%	Run the gradient descent
[theta, J_history] = gradientDescent(X, y, theta, alpha, iterations);
%   Open a new figure window
figure;
% 	Plot the convergence graph
%	Options: 'b' --- blue
plot(1:numel(J_history), J_history, '-b', 'LineWidth', 2);
% 	Set the x−axis label
xlabel('Number of iterations');
% 	Set the y−axis label
ylabel('Cost J');
%	Display the gradient descent's result
fprintf('Theta computed from gradient descent:\n');
fprintf('%f    ', theta);
fprintf('\n');
%   Pause the program
fprintf('Program paused. Press any key to continue.\n'); pause;

%	========	Part 3: Estimating Prices	========
%	Temp data
temp = [1650, 3];
%	Normalize the temp data of each feature
for i = 1:size(temp, 2),
    temp(:,i) -= mu(i);
    temp(:,i) /= sigma(i);
end;
%	Add one to temp
temp = [1, temp];
%	Predict the result with the trained theta
price = temp * theta;
fprintf('Predicted price of a 1650 sq-ft, 3 br house(using gradient descent):\n		$%f\n', price);
%   Pause the program
fprintf('Program paused. Press any key to continue.\n'); pause;

%	========	Part 4: Normal Equation		========
fprintf('Solving with normal equations...\n');
%	Load the data --- read comma separated data
data = csvread('data2.txt');
%   Initialize the variables of data
X = data(:, 1:2);
y = data(:, 3);
%   Number of the training examples
m = length(y);
%   Add a column of ones to X
X = [ones(m, 1), X];
%	Train the parameters from the normal equation
theta = normalEquation(X, y);
% 	Display the normal equation's result
fprintf('Theta computed from gradient descent:\n');
fprintf('%f    ', theta);
fprintf('\n');
%	Predict the result with the trained theta
price = [1, 1650, 3] * theta;
fprintf('Predicted price of a 1650 sq-ft, 3 br house(using normal equations):\n		$%f\n', price);
